﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Web;
using System.Web.Mvc;
using System.Data;
using System.Data.SqlClient;
using TBM.Filters;
using TBM.Attributes;

namespace TBM.Controllers
{
    public partial class MailController : MasterController
    {
        /// <summary>
        /// 收件箱
        /// </summary>
        /// <returns></returns>
        [Description("邮件管理")]
        [TBMAuthorize("邮件管理", "邮件管理")]
        public ActionResult Index()
        {
            if (IsAjaxRequest)
            {
                string type = Core.CommandParamType.NullOrString(Request["mailbox"]).ToString().ToLower();
                cmd.Parameters.Clear();
                cmd.CommandText = "p_GetMails";
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add("@Own", SqlDbType.VarChar, 15);
                cmd.Parameters.Add("@MailFrom", SqlDbType.VarChar, 15);
                cmd.Parameters.Add("@MailTo", SqlDbType.VarChar, 15);
                cmd.Parameters.Add("@Deleted", SqlDbType.Bit);
                cmd.Parameters.Add("@IsDraft", SqlDbType.Bit);
                cmd.Parameters.Add("@PageSize", SqlDbType.Int);
                cmd.Parameters.Add("@CurrPage", SqlDbType.Int);
                cmd.Parameters.Add("@RecordCount", SqlDbType.Int);
                cmd.Parameters["@RecordCount"].Direction = ParameterDirection.Output;
                ViewBag.IsDraft = false;
                ViewBag.IsInbox = false;
                ViewBag.IsTrash = false;

                switch (type)
                {
                    case "send":
                        // 发件箱
                        cmd.Parameters["@MailFrom"].Value = CurrUser.UID;
                        break;
                    case "trash":
                        // 垃圾箱
                        cmd.Parameters["@Deleted"].Value = true;
                        cmd.Parameters["@IsDraft"].Value = DBNull.Value;
                        ViewBag.IsTrash = true;
                        break;
                    case "draft":
                        // 草稿箱
                        cmd.Parameters["@MailFrom"].Value = CurrUser.UID;
                        cmd.Parameters["@IsDraft"].Value = true;
                        ViewBag.IsDraft = true;
                        break;
                    default:
                        // 收件箱
                        cmd.Parameters["@MailTo"].Value = CurrUser.UID;
                        ViewBag.IsInbox = true;
                        break;
                }

                List<Models.MailItem> mails = new List<Models.MailItem>();
                TBM.Tools.MailBoxNav mbn = new Tools.MailBoxNav("p", Core.Config.PageSize, 0);
                cmd.Parameters["@PageSize"].Value = mbn.PageSize;
                cmd.Parameters["@CurrPage"].Value = mbn.CurrPage;
                cmd.Parameters["@Own"].Value = CurrUser.UID;

                using (SqlDataReader dr = cmd.ExecuteReader())
                {
                    while (dr.Read())
                    {
                        mails.Add(new Models.MailItem
                        {
                            ID = (long)dr["ID"],
                            MailTo = dr["MailTo"].ToString(),
                            Subject = dr["Subject"].ToString(),
                            CreateDate = Convert.ToDateTime(dr["CreateDate"]),
                            MarkRead = (bool)dr["MarkRead"]
                        });
                    }
                }

                mbn.Count = (int)cmd.Parameters["@RecordCount"].Value;
                mbn.TextTemplate = "{currcount}-{currpagecount} / {count}";

                ViewBag.Mails = mails;
                ViewBag.Nav = mbn.Create();
                ViewBag.NavText = mbn.TextTemplate;

                return PartialView("List");
            }
            else
            {
                cmd.CommandText = @"select COUNT(*) as InBoxMailCount from dbo.Mail as M inner join dbo.UserMail as UM on M.MID = UM.MID 
	                                where M.MailTo = @UID and UM.UID = @UID and UM.MarkDeleted = 0 and UM.MarkRead = 0";
                cmd.CommandType = CommandType.Text;
                cmd.Parameters.Clear();
                cmd.Parameters.Add("@UID", SqlDbType.VarChar);
                cmd.Parameters["@UID"].Value = CurrUser.UID;

                ViewBag.InBoxMailCount = Convert.ToInt32(cmd.ExecuteScalar());

                return View();
            }
        }


        [ChildActionOnly]
        public ActionResult List()
        {
            return PartialView();
        }


        [ParentAction("Index")]
        [Description("[已/未]读标记")]
        [TBMAuthorize("邮件管理", "[已/未]读标记")]
        public JsonResult MarkRead(bool read, long[] mid)
        {
            JsonResult result = new JsonResult();

            cmd.CommandText = "update dbo.UserMail set MarkRead = @MarkRead where UID = @UID and MID in (select Item from fn_Split(@MID, ','))";
            cmd.CommandType = CommandType.Text;
            cmd.Parameters.Clear();
            cmd.Parameters.Add("@UID", SqlDbType.VarChar, 15);
            cmd.Parameters.Add("@MID", SqlDbType.VarChar, 1000);
            cmd.Parameters.Add("@MarkRead", SqlDbType.Bit);
            cmd.Parameters["@UID"].Value = CurrUser.UID;
            cmd.Parameters["@MID"].Value = String.Join(",", mid);
            cmd.Parameters["@MarkRead"].Value = read;

            Core.LangItem li = cmd.ExecuteNonQuery() > 0 ? Core.Lang.CMD_SUCCESS : Core.Lang.CMD_FAILED;

            cmd.CommandText = @"select COUNT(*) as InBoxMailCount from dbo.Mail as M inner join dbo.UserMail as UM on M.MID = UM.MID 
	                                where M.MailTo = @UID and UM.UID = @UID and UM.MarkDeleted = 0 and UM.MarkRead = 0";
            cmd.CommandType = CommandType.Text;
            cmd.Parameters.Clear();
            cmd.Parameters.Add("@UID", SqlDbType.VarChar);
            cmd.Parameters["@UID"].Value = CurrUser.UID;

            result.Data = new Models.ExecuteResult
            {
                Result = li.Code == Core.Lang.CMD_SUCCESS.Code,
                Code = li.Code,
                Message = li.Message,
                Data = new
                {
                    UnReadCount = Convert.ToInt32(cmd.ExecuteScalar())
                }
            };

            return result;
        }


        [ParentAction("Index")]
        [Description("临时删除")]
        [TBMAuthorize("邮件管理", "临时删除")]
        public JsonResult MarkDelete(long[] mid)
        {
            return _ChangeDeleteStatus(mid, true);
        }


        [ParentAction("Index")]
        [Description("永久删除")]
        [TBMAuthorize("邮件管理", "永久删除")]
        public JsonResult Delete(long[] mid)
        {
            JsonResult result = new JsonResult();

            cmd.CommandText = "p_DeleteMail";
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Clear();
            cmd.Parameters.Add("@Own", SqlDbType.VarChar, 15);
            cmd.Parameters.Add("@MID", SqlDbType.VarChar, 1000);
            cmd.Parameters["@Own"].Value = CurrUser.UID;
            cmd.Parameters["@MID"].Value = String.Join(",", mid);

            Core.LangItem li = cmd.ExecuteNonQuery() > 0 ? Core.Lang.CMD_SUCCESS : Core.Lang.CMD_FAILED;

            result.Data = new Models.ExecuteResult
            {
                Result = li.Code == Core.Lang.CMD_SUCCESS.Code,
                Code = li.Code,
                Message = li.Message
            };

            return result;
        }


        [ParentAction("Index")]
        [Description("恢复邮件")]
        [TBMAuthorize("邮件管理", "恢复邮件")]
        public JsonResult Restore(long[] mid)
        {
            return _ChangeDeleteStatus(mid, false);
        }


        /// <summary>
        /// 改变删除状态
        /// </summary>
        /// <param name="mid"></param>
        /// <param name="?"></param>
        /// <returns></returns>
        private JsonResult _ChangeDeleteStatus(long[] mid, bool isDelete)
        {
            JsonResult result = new JsonResult();

            cmd.CommandText = "update dbo.UserMail set MarkDeleted = @Delete where UID = @UID and MID in (select Item from fn_Split(@MID, ','))";
            cmd.CommandType = CommandType.Text;
            cmd.Parameters.Clear();
            cmd.Parameters.Add("@UID", SqlDbType.VarChar, 15);
            cmd.Parameters.Add("@MID", SqlDbType.VarChar, 1000);
            cmd.Parameters.Add("@Delete", SqlDbType.Bit);
            cmd.Parameters["@UID"].Value = CurrUser.UID;
            cmd.Parameters["@MID"].Value = String.Join(",", mid);
            cmd.Parameters["@Delete"].Value = isDelete;

            Core.LangItem li = cmd.ExecuteNonQuery() > 0 ? Core.Lang.CMD_SUCCESS : Core.Lang.CMD_FAILED;

            cmd.CommandText = @"select COUNT(*) as InBoxMailCount from dbo.Mail as M inner join dbo.UserMail as UM on M.MID = UM.MID 
	                                where M.MailTo = @UID and UM.UID = @UID and UM.MarkDeleted = 0 and UM.MarkRead = 0";
            cmd.CommandType = CommandType.Text;
            cmd.Parameters.Clear();
            cmd.Parameters.Add("@UID", SqlDbType.VarChar);
            cmd.Parameters["@UID"].Value = CurrUser.UID;

            result.Data = new Models.ExecuteResult
            {
                Result = li.Code == Core.Lang.CMD_SUCCESS.Code,
                Code = li.Code,
                Message = li.Message,
                Data = new
                {
                    UnReadCount = Convert.ToInt32(cmd.ExecuteScalar())
                }
            };

            return result;
        }
    }
}
